package jus.aor.mobilagent.kernel;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarException;

public class BAMLoader extends URLClassLoader {
	

	private HashMap<String,byte[]> buf = new HashMap<String,byte[]>();
	private Jar jar;
	
	public BAMLoader() {
		super(new URL[]{},null);
	}	
	public BAMLoader(ClassLoader loader) {
		super(new URL[]{},loader);
	}
	
	public Jar extractCode(){
		return jar;
	}
	
	public Class<?> findClass(String name) throws ClassNotFoundException{
		
		
		try{
			return super.findClass(Jar.formatClassName(name));
		}catch (ClassNotFoundException e){
			byte[] c = buf.get(Jar.formatClassName(name));
			if(c==null){
				throw e;
			}else{
				return defineClass(name, c, 0, c.length);
			}
		}
	}
	

	public void addURL(URL url){
		try {
			Jar prov = new Jar(url.getFile());
			intergrecode(prov);
		} catch (JarException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void intergrecode(Jar j){
		this.jar=j;
		for(Map.Entry<String,byte[]>  e: j.classIterator()){
			String name = e.getKey();
			byte[] clazz = e.getValue();
			buf.put(name, clazz);
		}
		
	}
}
